import React, { useContext, useEffect, useRef, useState } from 'react';
import { message, Card, Col, Row, Button } from 'antd';
import * as echarts from 'echarts';
import './index.css';
import LittleHeader from '../../components/LittleHeader';
import { useTranslation } from 'react-i18next';
import MainLayout from '../../components/MainLayout';
import withAuth from '../../components/WithAuth';
import ThemeContext from '@/theme/ThemeContext';
import axios from 'axios';

const Dashboard = () => {
    const { t } = useTranslation();
    const chartRef1 = useRef(null);
    const chartRef2 = useRef(null);
    const { theme } = useContext(ThemeContext);
    const chartInstances = useRef([]);
    const [loading, setLoading] = useState(false);
    const [packageData, setPackageData] = useState({
        dates: [
            '2023-10-01 09:30',
            '2023-10-02 14:15',
            '2023-10-03 11:45',
            '2023-10-04 16:20',
            // 最后一个动态获取（初始占位）
            new Date().toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                hour12: false
            }).replace(/\//g, '-').replace(',', '')
        ],
        counts: [3, 3, 6, 9, 0] // 最后一个初始为0，动态填充
    });

    // 根据主题获取配色方案
    const getThemeOptions = (isDark) => {
        return {
            textColor: isDark ? 'rgba(255, 255, 255, 0.85)' : 'rgba(0, 0, 0, 0.85)',
            axisLine: {
                lineStyle: {
                    color: isDark ? 'rgba(255, 255, 255, 0.3)' : 'rgba(0, 0, 0, 0.3)'
                }
            },
            splitLine: {
                lineStyle: {
                    color: isDark ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.1)'
                }
            },
            areaColors: isDark ? [
                ['#003366', '#4cabce'],
                ['#d94e5d', '#eac736'],
                ['#50a3ba', '#eac736'],
                ['#dd8668', '#eac736'],
                ['#c12e34', '#e6b600']
            ] : [
                ['#c6e2ff', '#5b9bd5'],
                ['#f8d7da', '#dc3545'],
                ['#d4edda', '#28a745'],
                ['#fff3cd', '#ffc107'],
                ['#e2e3e5', '#6c757d']
            ]
        };
    };

    // 获取最新的软件包数量（只执行一次）
    const fetchLatestPackageCount = async () => {
        setLoading(true);
        try {
            const token = localStorage.getItem('enc_token');
            const response = await axios.post('/api/v1/pkg/query',
                { page: 1, size: 1000 },
                { headers: { 'Authorization': token } }
            );

            if (response.data?.code === 0) {
                const packages = response.data.data?.list || response.data.data || [];
                const newCount = packages.length;

                setPackageData(prev => ({
                    ...prev,
                    dates: [...prev.dates.slice(0, 4),
                    new Date().toLocaleString('zh-CN', {
                        year: 'numeric',
                        month: '2-digit',
                        day: '2-digit',
                        hour: '2-digit',
                        minute: '2-digit',
                        hour12: false
                    }).replace(/\//g, '-').replace(',', '')],
                    counts: [...prev.counts.slice(0, 4), newCount]
                }));

            } else if ([1003, 1001, 1002].includes(response.data.code)) {
                message.error(t('Token失效，请重新登录'));
            }
        } catch (error) {
            console.error('获取软件包数据失败:', error);
            message.error(t('获取数据失败'));
        } finally {
            setLoading(false);
        }
    };

    // 初始化图表（只执行一次）
    const initCharts = () => {
        const isDark = theme === 'dark';
        const themeOptions = getThemeOptions(isDark);

        // 第一个图表配置
        const option1 = {
            backgroundColor: isDark ? '#141414' : '#fff',
            textStyle: {
                color: themeOptions.textColor
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross',
                    label: {
                        backgroundColor: isDark ? '#6a7985' : '#eee'
                    }
                }
            },
            legend: {
                textStyle: {
                    color: themeOptions.textColor
                },
                data: ['critical', 'high', 'medium', 'low', 'negligible']
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                axisLine: {
                    lineStyle: {
                        color: themeOptions.axisLine.lineStyle.color
                    }
                },
                axisLabel: {
                    color: themeOptions.textColor
                },
                data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
            },
            yAxis: {
                type: 'value',
                axisLine: {
                    lineStyle: {
                        color: themeOptions.axisLine.lineStyle.color
                    }
                },
                axisLabel: {
                    color: themeOptions.textColor
                },
                splitLine: {
                    lineStyle: {
                        color: themeOptions.splitLine.lineStyle.color
                    }
                }
            },
            series: [
                {
                    name: 'critical',
                    type: 'line',
                    stack: 'Total',
                    areaStyle: {},
                    emphasis: {
                        focus: 'series'
                    },
                    data: [120, 132, 101, 134, 90, 230, 210]
                },
                {
                    name: 'high',
                    type: 'line',
                    stack: 'Total',
                    areaStyle: {},
                    emphasis: {
                        focus: 'series'
                    },
                    data: [220, 182, 191, 234, 290, 330, 310]
                },
                {
                    name: 'medium',
                    type: 'line',
                    stack: 'Total',
                    areaStyle: {},
                    emphasis: {
                        focus: 'series'
                    },
                    data: [150, 232, 201, 154, 190, 330, 410]
                },
                {
                    name: 'low',
                    type: 'line',
                    stack: 'Total',
                    areaStyle: {},
                    emphasis: {
                        focus: 'series'
                    },
                    data: [320, 332, 301, 334, 390, 330, 320]
                },
                {
                    name: 'negligible',
                    type: 'line',
                    stack: 'Total',
                    label: {
                        show: true,
                        position: 'top'
                    },
                    areaStyle: {},
                    emphasis: {
                        focus: 'series'
                    },
                    data: [820, 932, 901, 934, 1290, 1330, 1320]
                }
            ]
        };

        // 第二个图表配置
        const option2 = {
            backgroundColor: isDark ? '#141414' : '#fff',
            textStyle: {
                color: themeOptions.textColor
            },
            tooltip: {
                trigger: 'axis',
                formatter: (params) => {
                    const data = params[0];
                    return `时间: ${packageData.dates[data.dataIndex]}<br/>软件包数量: ${data.value}`;
                }
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                axisLine: {
                    lineStyle: {
                        color: themeOptions.axisLine.lineStyle.color
                    }
                },
                axisLabel: {
                    color: themeOptions.textColor,
                    formatter: (value) => {
                        const [date, time] = value.split(' ');
                        return `${date.substring(5)} ${time}`;
                    },
                    rotate: 30
                },
                data: packageData.dates
            },
            yAxis: {
                type: 'value',
                axisLine: {
                    lineStyle: {
                        color: themeOptions.axisLine.lineStyle.color
                    }
                },
                axisLabel: {
                    color: themeOptions.textColor
                },
                splitLine: {
                    lineStyle: {
                        color: themeOptions.splitLine.lineStyle.color
                    }
                }
            },
            series: [
                {
                    data: packageData.counts,
                    type: 'line',
                    areaStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            {
                                offset: 0,
                                color: isDark ? 'rgba(58, 77, 233, 0.8)' : 'rgba(58, 77, 233, 0.3)'
                            },
                            {
                                offset: 1,
                                color: isDark ? 'rgba(58, 77, 233, 0.1)' : 'rgba(58, 77, 233, 0.01)'
                            }
                        ])
                    },
                    lineStyle: {
                        color: '#3a4de9'
                    },
                    itemStyle: {
                        color: '#3a4de9'
                    },
                    smooth: true,
                    symbol: 'circle',
                    symbolSize: 8
                }
            ]
        };

        // 初始化图表
        if (chartRef1.current) {
            const chart1 = echarts.init(chartRef1.current, isDark ? 'dark' : null);
            chart1.setOption(option1);
            chartInstances.current[0] = chart1;
        }

        if (chartRef2.current) {
            const chart2 = echarts.init(chartRef2.current, isDark ? 'dark' : null);
            chart2.setOption(option2);
            chartInstances.current[1] = chart2;
        }
    };

    // 组件加载时只执行一次初始化
    useEffect(() => {
        initCharts();
        fetchLatestPackageCount();

        // 只保留窗口resize监听
        const handleResize = () => {
            chartInstances.current.forEach(chart => chart?.resize());
        };
        window.addEventListener('resize', handleResize);
        return () => window.removeEventListener('resize', handleResize);
    }, []);

    return (
        <MainLayout defaultSelectedKey="2">
            <LittleHeader />
            <Row style={{ marginTop: 30 }}>
                <Col span={24}>
                    <Card title={t("总漏洞数量分布")} style={{ width: '100%' }}>
                        <div ref={chartRef1} style={{ width: '100%', height: '400px' }} />
                    </Card>
                </Col>
            </Row>
            <Row style={{ marginTop: 30 }}>
                <Col span={24}>
                    <Card
                        title={t("项目")}
                        style={{ width: '100%' }}
                    >
                        <div ref={chartRef2} style={{ width: '100%', height: '300px' }} />
                    </Card>
                </Col>
            </Row>
        </MainLayout>
    );
};

export default withAuth(Dashboard);
